package com.um.systemmonitor.cpumonitor;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.Button;
import android.widget.TextView;

import com.um.systemmonitor.R;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

public class ChartViewerActivity extends Activity {
    private static final String TAG = "ChartViewer";
    
    private LineChart cpuTempChart;
    private LineChart freqChart;
    private LineChart memoryChart;
    private TextView tvFileInfo, tvTimeRange;
    private Button btnBack;
    
    private String filePath;
    private String dataType;
    private String startTime, endTime;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chart_viewer);
        
        initViews();
        loadIntentData();
        loadAndDisplayData();
    }
    
    private void initViews() {
        cpuTempChart = findViewById(R.id.chart_cpu_temp);
        freqChart = findViewById(R.id.chart_frequency);
        memoryChart = findViewById(R.id.chart_memory);
        tvFileInfo = findViewById(R.id.tv_file_info);
        tvTimeRange = findViewById(R.id.tv_time_range);
        btnBack = findViewById(R.id.btn_back);
        
        btnBack.setOnClickListener(v -> finish());
        
        // 配置图表轴标签
        setupCharts();
    }
    
    private void setupCharts() {
        // CPU+温度图：左轴使用率%，右轴温度℃
        cpuTempChart.setLeftAxis("%", 100f);
        cpuTempChart.setRightAxisEnabled(true, "°C", 100f); // 温度上限100℃
        
        // 频率图：左轴MHz，上限3GHz
        freqChart.setLeftAxis("MHz", 3000f);
        
        // 内存图：左轴%，上限100%
        memoryChart.setLeftAxis("%", 100f);
    }
    
    private void loadIntentData() {
        filePath = getIntent().getStringExtra("file_path");
        dataType = getIntent().getStringExtra("data_type");
        startTime = getIntent().getStringExtra("start_time");
        endTime = getIntent().getStringExtra("end_time");
        
        if (filePath == null || dataType == null) {
            Log.e(TAG, "Missing required data");
            finish();
            return;
        }
        
        // 显示文件信息
        File file = new File(filePath);
        tvFileInfo.setText("文件: " + file.getName());
        
        // 显示时间范围
        if (startTime != null && endTime != null) {
            tvTimeRange.setText("时间范围: " + startTime + " - " + endTime);
        } else {
            tvTimeRange.setText("显示全部数据");
        }
    }
    
    private void loadAndDisplayData() {
        try {
            // 现在所有数据都在合并的system_data_文件中
            loadCpuData(); // 这个方法现在处理所有数据（CPU+内存）
        } catch (Exception e) {
            Log.e(TAG, "Error loading data", e);
        }
    }
    
    private void loadCpuData() throws IOException, ParseException {
        List<Float> cpuUsage = new ArrayList<>();
        List<Float> cpuTemp = new ArrayList<>();
        List<Float> cpuFreq = new ArrayList<>();
        List<Float> memoryUsage = new ArrayList<>();
        List<String> timeLabels = new ArrayList<>();
        
        BufferedReader reader = new BufferedReader(new FileReader(filePath));
        String line;
        boolean isHeader = true;
        
        while ((line = reader.readLine()) != null) {
            if (isHeader) {
                isHeader = false;
                continue;
            }
            
            String[] parts = line.split(",");
            if (parts.length >= 12) {
                String timeStr = parts[0];
                
                // 时间范围过滤
                if (startTime != null && endTime != null) {
                    try {
                        String timePart = timeStr.substring(0, 5);
                        if (timePart.compareTo(startTime) < 0 || timePart.compareTo(endTime) > 0) {
                            continue;
                        }
                    } catch (Exception e) {
                        Log.w(TAG, "Error comparing time: " + timeStr, e);
                        continue;
                    }
                }
                
                try {
                    cpuUsage.add(Float.parseFloat(parts[1]));
                    cpuFreq.add(Float.parseFloat(parts[2]));
                    cpuTemp.add(Float.parseFloat(parts[6]));
                    memoryUsage.add(Float.parseFloat(parts[7]));
                    timeLabels.add(timeStr);
                } catch (NumberFormatException e) {
                    Log.w(TAG, "Invalid number format: " + line);
                }
            }
        }
        reader.close();
        
        // 生成6个动态时间点，最右边为now
        List<String> dynamicTimeLabels = generateDynamicTimeLabels(timeLabels);
        
        // 设置历史数据模式
        cpuTempChart.setTimeAxisForHistoryData(dynamicTimeLabels);
        freqChart.setTimeAxisForHistoryData(dynamicTimeLabels);
        memoryChart.setTimeAxisForHistoryData(dynamicTimeLabels);
        
        // 加载数据
        cpuTempChart.loadHistoricalData(cpuUsage, cpuTemp, new ArrayList<>(), new ArrayList<>());
        freqChart.loadHistoricalData(new ArrayList<>(), new ArrayList<>(), cpuFreq, new ArrayList<>());
        memoryChart.loadHistoricalData(new ArrayList<>(), new ArrayList<>(), new ArrayList<>(), memoryUsage);
    }
    
    // 新增方法：生成6个动态时间点，时间间隔相同
    private List<String> generateDynamicTimeLabels(List<String> originalTimeLabels) {
        List<String> dynamicLabels = new ArrayList<>();
        
        if (originalTimeLabels == null || originalTimeLabels.isEmpty()) {
            // 如果没有数据，返回默认的6个时间点
            for (int i = 0; i < 7; i++) {
                dynamicLabels.add("--:--");
            }
            return dynamicLabels;
        }
        
        int totalPoints = originalTimeLabels.size();
        
        if (totalPoints < 2) {
            // 如果数据点少于2个，返回默认值
            for (int i = 0; i < 7; i++) {
                dynamicLabels.add("--:--");
            }
            return dynamicLabels;
        }
        
        // 获取最久和最新的时间戳
        String oldestTime = originalTimeLabels.get(0);
        String newestTime = originalTimeLabels.get(totalPoints - 1);
        
        // 统一处理：无论时间差多少，都生成6个等间隔的时间戳
        dynamicLabels = generateEqualIntervalTimeLabels(oldestTime, newestTime);
        
        return dynamicLabels;
    }

    // 生成6个等间隔的时间戳（合并后的版本）
    private List<String> generateEqualIntervalTimeLabels(String oldestTime, String newestTime) {
        List<String> labels = new ArrayList<>();
        
        try {
            SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm:ss", Locale.getDefault());
            Date oldest = timeFormat.parse(oldestTime);
            Date newest = timeFormat.parse(newestTime);
            
            long timeDiff = newest.getTime() - oldest.getTime();
            long interval = timeDiff / 6; // 6个间隔，7个时间点
            
            for (int i = 0; i < 7; i++) {
                long currentTime = oldest.getTime() + (interval * i);
                Date currentDate = new Date(currentTime);
                labels.add(timeFormat.format(currentDate));
            }
            
        } catch (ParseException e) {
            Log.e(TAG, "Error generating equal interval time labels", e);
            // 如果解析失败，返回原始时间标签
            labels.add(oldestTime);
            for (int i = 1; i < 8; i++) {
                labels.add("--:--");
            }
            labels.add(newestTime);
        }
        
        return labels;
    }
}
